package com.hsylient.test;

import lombok.Data;

import java.math.BigDecimal;
import java.util.concurrent.locks.Condition;
import java.util.concurrent.locks.ReentrantLock;

@Data
public class Bank {

    private BigDecimal balance;

    private ReentrantLock lock;

    private Condition condition;

    public Bank(BigDecimal balance) {
        this.balance = balance;
        this.lock = new ReentrantLock();
        this.condition = lock.newCondition();
    }

    public void transfer(BigDecimal amount, Bank bank) throws InterruptedException {
        lock.lock();
        try {
            if (balance.compareTo(amount) > 0) {
                this.balance = balance.subtract(amount);
                bank.setBalance(bank.getBalance().add(amount));
                condition.signalAll();
            } else {
                condition.await();
            }
        } finally {
            lock.unlock();
        }
    }
}
